package com.jzg.jcptadmin.ui;

import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.FileUtils;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.base.BaseActivity;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;



/**
 * PlayVideoActiviy
 *
 * @author sunbl
 *         created at 2016/2/3 16:53
 */
public class PlayVideoActiviy extends BaseActivity {
    public static final String KEY_FILE_PATH = "file_path";

    private String filePath;
    @Bind(R.id.video_view)
    VideoView mScalableVideoView;
    @Bind(R.id.playImageView)
    ImageView mPlayImageView;
    @Bind(R.id.loading)
    ViewStub loading;
    @Bind(R.id.title_content)
    TextView titleContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        filePath = getIntent().getStringExtra(KEY_FILE_PATH);
        if (TextUtils.isEmpty(filePath) || !filePath.endsWith("mp4")) {
            Toast.makeText(this, "视频路径错误", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        setContentView(R.layout.activity_play_video_activiy);
        ButterKnife.bind(this);
        titleContent.setText("视频播放");
        mScalableVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mScalableVideoView.seekTo(0);
                mScalableVideoView.pause();
                mPlayImageView.setVisibility(View.VISIBLE);
            }
        });
        mScalableVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                loading.setVisibility(View.GONE);
                finish();
                MyToast.showShort("视频播放失败");
                return false;
            }
        });
        mScalableVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                // TODO Auto-generated method stub
                //  mTextView01.setText(strVideoPath);
                loading.setVisibility(View.GONE);
            }
        });
        loading.setVisibility(View.VISIBLE);
        mScalableVideoView.setVideoURI(Uri.parse(filePath));
        mScalableVideoView.start();
//        playVideo();
    }

    /**
     * 获取视频缩略图（这里获取第一帧）
     *
     * @return
     */
    public Bitmap getVideoThumbnail() {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime(TimeUnit.MILLISECONDS.toMicros(1));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    @OnClick({R.id.video_view, R.id.playImageView})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.video_view:
                mScalableVideoView.pause();
                mPlayImageView.setVisibility(View.VISIBLE);
                break;
            case R.id.playImageView:
//                    mScalableVideoView.setDataSource(filePath);
                playVideo();


                break;
        }
    }

    private void playVideo() {
        mPlayImageView.setVisibility(View.GONE);
//        mScalableVideoView.setVideoURI(Uri.parse(filePath));
        mScalableVideoView.start();
//        loading.setVisibility(View.VISIBLE);
//        if (!filePath.startsWith("http")) {
//            mScalableVideoView.setVideoPath(filePath);
//            mScalableVideoView.start();
//            loading.setVisibility(View.GONE);
//        } else {
//            Observable.create(new Observable.OnSubscribe<Integer>() {
//                @Override
//                public void call(Subscriber<? super Integer> subscriber) {
//                    int i = downFile(filePath, Environment.getExternalStorageDirectory().getAbsolutePath()
//                            + "/JZGErShouChe/DownLoad/", "car.mp4");
//                    subscriber.onNext(i);
//                }
//            }).subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(new Subscriber<Integer>() {
//                        @Override
//                        public void onCompleted() {
//
//                        }
//
//                        @Override
//                        public void onError(Throwable e) {
//                            MyToast.showShort(Constant.ERROR_FORNET);
//                            finish();
//                        }
//
//                        @Override
//                        public void onNext(Integer integer) {
//                            if (integer == 0) {
//                                filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/JZGErShouChe/DownLoad/car.mp4";
//                                mScalableVideoView.setVideoPath(filePath);
//                                mScalableVideoView.start();
//                                loading.setVisibility(View.GONE);
//                            } else {
//                                Toast.makeText(PlayVideoActiviy.this, "视频无法播放", Toast.LENGTH_SHORT).show();
//                                MyToast.showShort("视频播放失败");
//                                finish();
//                            }
//                        }
//                    });
//        }
    }

    public int downFile(String urlStr, String path, String fileName) {
        InputStream inputStream = null;
        try {
            FileUtils fileUtils = new FileUtils(path);
            boolean bl = fileUtils.isFileExist(fileName);
            if (bl) {
                fileUtils.delete();
            }
            // inputStream = getInputStreamFromURL(urlStr);

            HttpURLConnection urlConn = null;

            int length;
            URL url = new URL(urlStr);
            urlConn = (HttpURLConnection) url.openConnection();
            inputStream = urlConn.getInputStream();
            length = urlConn.getContentLength();
            File resultFile = fileUtils.write2SDFromInput(path, fileName,
                    inputStream);
            if (resultFile == null) {
                return -1;
            }
            long str = resultFile.length();
            if (str != length) {
                return -1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }


}
